package com.example.myapplication.peripheral;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.myapplication.R;

import java.util.ArrayList;
import java.util.List;

public class DeviceListDialog extends Dialog {
    private List<BluetoothDevice> deviceList;
    private OnDeviceSelectedListener listener;
    private ArrayAdapter<String> adapter;

    public interface OnDeviceSelectedListener {
        void onDeviceSelected(BluetoothDevice device);
    }

    public DeviceListDialog(Context context, List<BluetoothDevice> devices, OnDeviceSelectedListener listener) {
        super(context);
        this.deviceList = devices;
        this.listener = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_device_list);
        setTitle("Select BLE Device");

        ListView listView = findViewById(R.id.device_list_view);
        adapter = new ArrayAdapter<>(getContext(),
                android.R.layout.simple_list_item_1,
                getDeviceNames());

        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            if (listener != null) {
                listener.onDeviceSelected(deviceList.get(position));
            }
            dismiss();
        });
    }

    // Add this method to update the list
    public void updateList(List<BluetoothDevice> newDevices) {
        this.deviceList = newDevices;
        if (adapter != null) {
            adapter.clear();
            adapter.addAll(getDeviceNames());
            adapter.notifyDataSetChanged();
        }
    }
    @SuppressLint("MissingPermission")
    private List<String> getDeviceNames() {
        List<String> names = new ArrayList<>();
        for (BluetoothDevice device : deviceList) {
            String name = device.getName();
            String address = device.getAddress();
            names.add(name != null ? name + " (" + address + ")" : "Unknown Device (" + address + ")");
        }
        return names;
    }
}